#include "crypto/ciphers/common.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void generate_random_iv(u8 *iv, int length)
{
	struct timespec ts;
	clock_gettime(CLOCK_REALTIME, &ts);
	u64 t = ((u64)ts.tv_sec) * 1000ULL * 1000ULL * 1000ULL + ((u64)ts.tv_nsec);

	int i;
	for (i = 0; i < length; i++) {
		iv[i] = 0;
	}
	copy(iv, &t, length < (int)sizeof(t) ? length : (int)sizeof(t));
}

// The memcpy implementation from libc is retarded.
// We use instead the implementation by Linus Torvlads, posted here:
// https://bugzilla.redhat.com/show_bug.cgi?id=638477#c38
void *copy(void *dst, const void *src, size_t size)
{
	void *orig = dst;
	asm volatile("rep ; movsq"
				 :"=D" (dst), "=S" (src)
				 :"0" (dst), "1" (src), "c" (size >> 3)
				 :"memory");
	asm volatile("rep ; movsb"
				 :"=D" (dst), "=S" (src)
				 :"0" (dst), "1" (src), "c" (size & 7)
				 :"memory");
	return orig;
}


void crash(const char *file, int line, const char *function, const char *message)
{
	fprintf(stderr, "error: %s %d %s: %s\n", file, line, function, message);
	exit(-1);
}
